package com.kingdee.eas.custom.common;

import java.text.Collator;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.Locale;

import com.kingdee.bos.ctrl.kdf.table.KDTCell;
import com.kingdee.bos.ctrl.kdf.table.KDTRow;
import com.kingdee.eas.basedata.person.PersonInfo;

public class TableCellComparator implements Comparator {

	int colIndex = 0;
	int sortType;
	Collator comparator = Collator.getInstance(Locale.getDefault());

	public TableCellComparator(int i, int sortType) {
		this.colIndex = i;
		this.sortType = sortType;
	}

	public int compare(Object kdtRow1, Object kdtRow2) {
		int result = doCompare(kdtRow1, kdtRow2);
		if (this.sortType == 0) {
			return result;
		}

		if (result < 0) {
			return 1;
		}
		if (result > 0) {
			return -1;
		}

		return result;
	}

	public int doCompare(Object kdtRow1, Object kdtRow2) {
		Object o1 = null;
		Object o2 = null;
		KDTCell cell = ((KDTRow) kdtRow1).getCell(this.colIndex);
		if (cell != null) {
			o1 = cell.getValue();
		}
		cell = ((KDTRow) kdtRow2).getCell(this.colIndex);
		if (cell != null) {
			o2 = cell.getValue();
		}
		if (o1 == o2) {
			return 0;
		}
		if ((o1 == null) && (o2 != null)) {
			return -1;
		}
		if ((o1 != null) && (o2 == null)) {
			return 1;
		}

		if (o1 instanceof Number) {
			if (o2 instanceof Number) {
				double d1 = ((Number) o1).doubleValue();
				double d2 = ((Number) o2).doubleValue();
				if (d1 == d2) {
					return 0;
				}
				if (d1 < d2) {
					return -1;
				}

				return 1;
			}

			return o1.toString().compareTo(o2.toString());
		}

		if (o1 instanceof String) {
			if (o2 instanceof String) {
				return this.comparator.compare(o1, o2);
			}

			return ((String) o1).compareTo(o2.toString());
		}

		if (o1 instanceof Date) {
			if (o2 instanceof Date) {
				return ((Date) o1).compareTo((Date) o2);
			}

			return o1.toString().compareTo(o2.toString());
		}

		if (o1 instanceof Calendar) {
			if (o2 instanceof Calendar) {
				long d1 = ((Calendar) o1).getTimeInMillis();
				long d2 = ((Calendar) o2).getTimeInMillis();
				if (d1 == d2) {
					return 0;
				}
				if (d1 < d2) {
					return -1;
				}

				return 1;
			}

			return o1.toString().compareTo(o2.toString());
		}

		if (o1 instanceof PersonInfo) {
			if (o2 instanceof PersonInfo) {
				String n1 = ((PersonInfo) o1).getNumber();
				String n2 = ((PersonInfo) o2).getNumber();

				return n1.compareTo(n2);
			}
		}
		if (o1 instanceof Comparable) {
			if (o2 instanceof Comparable) {
				return ((Comparable) o1).compareTo((Comparable) o2);
			}

			return o1.toString().compareTo(o2.toString());
		}

		return o1.toString().compareTo(o2.toString());
	}
}
